﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using Devv.Core.Utils;
using Devv.FreshTracker.Entity;
using Devv.FreshTracker.Properties;

namespace Devv.FreshTracker
{
	public partial class RulesForm : Form
	{
		#region Properties

		private Boolean EscPressed { get; set; }
		private Boolean NotesAdded { get; set; }

		#endregion

		#region Constructor and loading

		public RulesForm()
		{
			InitializeComponent();

			Icon = Resources.App;
		}

		private void RulesForm_Load(object sender, EventArgs e)
		{
			if (!Options.IsLoginSet)
			{
				MessageBox.Show(Messages.WarningLoginNotSet, Messages.LoginDetails, MessageBoxButtons.OK, MessageBoxIcon.Information);
				Close();

				Program.ShowOptionsForm();

				return;
			}

			if (LocalCache.Tasks.Count < 1)
			{
				RefreshData();
			}
			else
			{
				cboTasks.DataSource = LocalCache.Tasks;
				cboTasks.DisplayMember = "FullDisplayMember";
				cboTasks.SelectedIndex = 0;
			}

			gridRules.AutoGenerateColumns = false;
			gridRules.DataSource = LocalCache.Rules;

			SetStatus(Options.EnableRules);
		}

		private void RulesForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			for (Int32 i = 0; i < gridRules.Rows.Count; i++)
			{
				DataGridViewCheckBoxCell del = gridRules["colDelete", i] as DataGridViewCheckBoxCell;

				if (Convert.ToBoolean(del.Value))
				{
					gridRules.Rows.RemoveAt(i);
				}
			}

			LocalCache.SaveRule();

			if (!Program.Closing && Options.EnableRules)
			{
				AutoTracking.Start();
			}

			Dispose();
		}

		private void RulesForm_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
		{
			if (e.KeyCode == Keys.Escape)
			{
				if (EscPressed)
				{
					CancelSave();
				}
				else
				{
					EscPressed = true;
				}
			}
		}

		#endregion

		#region Add rules

		private void imgAddRule_Click(object sender, EventArgs e)
		{
			if (String.IsNullOrEmpty(txtWindowTitle.Text))
			{
				MessageBox.Show(Messages.EnterRuleWindowTitle, Messages.Warning, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
				txtWindowTitle.Focus();

				return;
			}
			
			if (cboTasks.SelectedIndex < 0)
			{
				return;
			}

			for (Int32 i = 0; i < LocalCache.Rules.Count; i++)
			{
				String code = Rule.GetCode(txtWindowTitle.Text);

				if (LocalCache.Rules[i].Code.Contains(code) && MessageBox.Show(Messages.ConfirmRuleWindowTitleDup.Replace("#", LocalCache.Rules[i].WindowTitle), Messages.Confirm, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
				{
					return;
				}
			}

			Rule r = new Rule();

			r.WindowTitle = txtWindowTitle.Text.Trim();
			r.Task = cboTasks.SelectedItem as Task;
			r.Enabled = true;

			LocalCache.Rules.Add(r);

			gridRules.DataSource = LocalCache.Rules;
			gridRules.Refresh();

			txtWindowTitle.Text = String.Empty;
		}

		#endregion

		#region Rules grid

		private void gridRules_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
		{
			if (e.ListChangedType == ListChangedType.Reset)
			{
				for (Int32 i = 0; i < gridRules.Rows.Count; i++)
				{
					String hours = "00:00";
					Session s = AutoTracking.Sessions.Find(((Rule)gridRules.Rows[i].DataBoundItem).Task);

					if (s != null)
					{
						hours = DataUtil.TimespanToTime(TimeSpan.FromSeconds(s.TempSeconds), ":");
					}

					gridRules["colCurrentSession", i].Value = hours;
				}
			}
		}

		private void gridRules_CellEnter(object sender, DataGridViewCellEventArgs e)
		{
			if (gridRules.Columns[e.ColumnIndex].Name == "colNotes")
			{
				gridRules.BeginEdit(false);
			}
		}

		private void gridRules_CellValueChanged(object sender, DataGridViewCellEventArgs e)
		{
			if (e.ColumnIndex < 0 || e.RowIndex < 0)
			{
				return;
			}

			DataGridViewColumn col = gridRules.Columns[e.ColumnIndex];
			DataGridViewRow row = gridRules.Rows[e.RowIndex];
			DataGridViewCell cell = gridRules[e.ColumnIndex, e.RowIndex];

			if (gridRules.Columns[e.ColumnIndex].Name == "colNotes")
			{
				Session s = AutoTracking.Sessions.Find(((Rule)gridRules.Rows[e.RowIndex].DataBoundItem).Task);

				if (s != null)
				{
					s.Notes = cell.Value.ToString();
				}

				NotesAdded = true;
			}
			else if (col.Name == "colDelete")
			{
				if (Convert.ToBoolean(cell.Value))
				{
					row.DefaultCellStyle.BackColor = Color.LightPink;
				}
				else
				{
					row.DefaultCellStyle.BackColor = SystemColors.Window;
				}

				gridRules.Refresh();
			}
			else if (col.Name == "colEnabled")
			{
				if (Convert.ToBoolean(cell.Value))
				{
					row.DefaultCellStyle.ForeColor = SystemColors.WindowText;
				}
				else
				{
					row.DefaultCellStyle.ForeColor = SystemColors.GrayText;
				}

				gridRules.Refresh();
			}
		}

		private void timerRefresh_Tick(object sender, EventArgs e)
		{
			gridRules.Refresh();
		}

		#endregion

		#region Status

		private void imgStatus_Click(object sender, EventArgs e)
		{
			SetStatus(!Options.EnableRules);
		}

		public void SetStatus(Boolean enabled)
		{
			Options.EnableRules = enabled;
			gridRules.Enabled = enabled;

			if (enabled)
			{
				imgStatus.Image = Resources.IcoRulesOn32;
				lblStatus.Text = Messages.Enabled;

				timerRefresh.Start();
				AutoTracking.Start();
			}
			else
			{
				imgStatus.Image = Resources.IcoRulesOff32;
				lblStatus.Text = Messages.Disabled;

				timerRefresh.Stop();
				AutoTracking.Stop();
			}

			Program.MainFormObj.SetAutoTracking();
		}

		#endregion

		#region Save and upload

		private void panSave_Click(object sender, EventArgs e)
		{
			if (AutoTracking.Sessions.Count < 1)
			{
				return;
			}

			NotesAdded = false;

			if (Options.ShowNotes)
			{
				ShowNotes();
			}
			else
			{
				SaveAndUpload();
			}
		}

		private void panAddNotes_Click(object sender, EventArgs e)
		{
			if (!NotesAdded && MessageBox.Show(Messages.WarningNoNotesAdded, Messages.Warning, MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
			{
				return;
			}

			SaveAndUpload();
		}

		private void workerUpload_DoWork(object sender, DoWorkEventArgs e)
		{
			AutoTracking.Save();
		}

		private void workerUpload_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			ResetGrid();
		}

		public void ShowNotes()
		{
			for (Int32 i = 0; i < gridRules.Rows.Count; i++)
			{
				Boolean editable = !Convert.ToBoolean(gridRules["colDelete", i].Value) && Convert.ToBoolean(gridRules["colEnabled", i].Value);

				if (editable && gridRules["colCurrentSession", i].Value.ToString() != "00:00")
				{
					gridRules["colNotes", i].ReadOnly = false;
				}
				else
				{
					gridRules["colNotes", i].ReadOnly = true;
				}
			}

			colWindowTitle.Visible = false;
			colDelete.Visible = false;
			colEnabled.Visible = false;
			colNotes.Visible = true;

			lblSaveInfo.Visible = false;
			panSave.Visible = false;
			panAddNotes.Visible = true;
			panNoteCancel.Visible = true;

			toolTips.Show(Messages.AddNotesToGrid, gridRules);

			AutoTracking.Stop();
		}

		public void SaveAndUpload()
		{
			gridRules.Enabled = false;

			workerUpload.RunWorkerAsync();
		}

		public void CancelSave()
		{
			if (workerUpload.IsBusy)
			{
				return;
			}

			ResetGrid();
		}

		public void ResetGrid()
		{
			gridRules.Enabled = true;

			colNotes.Visible = false;
			colWindowTitle.Visible = true;
			colDelete.Visible = true;
			colEnabled.Visible = true;

			panNoteCancel.Visible = false;
			panAddNotes.Visible = false;
			panSave.Visible = true;
			lblSaveInfo.Visible = true;

			gridRules.DataSource = LocalCache.Rules;

			if (Options.EnableRules)
			{
				AutoTracking.Start();
			}
		}

		#endregion

		#region Cancel adding

		private void panNoteCancel_Click(object sender, EventArgs e)
		{
			CancelSave();
		}

		#endregion

		#region General data refresh

		private void workerRefreshData_DoWork(object sender, DoWorkEventArgs e)
		{
			LocalCache.Refresh();
		}

		private void workerRefreshData_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			cboTasks.DataSource = LocalCache.Tasks;
			cboTasks.DisplayMember = "FullDisplayMember";
			cboTasks.Enabled = true;

			if (LocalCache.Tasks.Count > 0)
			{
				cboTasks.SelectedIndex = 0;
			}

			txtWindowTitle.Enabled = true;
			lblLoadingTasks.Visible = false;
		}

		private void RefreshData()
		{
			cboTasks.Enabled = false; 
			txtWindowTitle.Enabled = false;
			lblLoadingTasks.Visible = true;

			workerRefreshData.RunWorkerAsync();
		}

		#endregion
	}
}